package com.zgc.view.controller;

import com.fx.spring.annotation.ControllerFX;
import com.fx.spring.controller.AbstractController;
import com.jfoenix.controls.JFXListView;
import com.zgc.cache.ConnectionInfoCache;
import com.zgc.cache.CuratorClientCache;
import com.zgc.util.CuratorZkUtil;
import com.zgc.view.cell.ConnectListViewCell;
import com.zgc.view.common.ContextMenuCtrl;
import com.zgc.zkinfo.ZkConnectionInfo;
import com.zgc.zkinfo.ZkService;
import com.zgc.zkinfo.ZkServiceFactory;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.VBox;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.ResourceBundle;

@ControllerFX(fxmlURL = "/view/fxml/ConnectListView.fxml")
public class ConnectListViewCtrl extends AbstractController<VBox> {

    @FXML
    private JFXListView<ZkConnectionInfo> connectListView;


    @Autowired
    private ProgressAlertCtrl progressAlertCtrl;
    @Autowired
    private ContextMenuCtrl contextMenuCtrl;
    @Autowired
    private InformationTableCtrl informationTableCtrl;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        logger.debug("[{}]初始化完成", location);
        initListView();
        bindingsConnectList();
        initListViewSelect();
    }

    /**
     * 初始化ListView选择事件
     */
    private void initListViewSelect() {
        MultipleSelectionModel<ZkConnectionInfo> selectionModel = connectListView.getSelectionModel();
        //失去焦点时清除选择的tree
        connectListView.focusedProperty().addListener((obv, ov, nv) -> {
            if (!nv) {
                selectionModel.clearSelection();
            }
        });
        // 双击获取当前选择的 连接
        connectListView.setOnMouseClicked(event -> {
            ZkConnectionInfo selectedItem = selectionModel.getSelectedItem();
            if (selectedItem != null && MouseButton.PRIMARY.equals(event.getButton()) && event.getClickCount() == 2) {
                connect(selectedItem);
            }
        });
    }

    /**
     * 初始化ListView
     */
    private void initListView() {
        connectListView.setContextMenu(contextMenuCtrl.load());
        connectListView.setCellFactory(listView -> new ConnectListViewCell(this));
        /*// 开启间隙
        connectListView.setExpanded(true);
        // 垂直间隙
        connectListView.setVerticalGap(10.0);
        // 阴影深度
        connectListView.setDepth(1);*/
    }

    /**
     * 添加zookeeper连接
     */
    private void bindingsConnectList() {
        ObservableMap<String, ZkConnectionInfo> zkConnectMap = ConnectionInfoCache.zkConnectMap();
        ObjectBinding<ObservableList<ZkConnectionInfo>> objectBinding = Bindings.createObjectBinding(() -> FXCollections.observableArrayList(zkConnectMap.values()), zkConnectMap);
        connectListView.itemsProperty().bind(objectBinding);
    }


    /**
     * 连接
     *
     * @param connectionInfo 当前选择的客户端
     */
    public void connect(ZkConnectionInfo connectionInfo) {
        logger.debug("当前选择的连接[{}]", connectionInfo);
        CuratorFramework curatorZkClient = CuratorClientCache.getCuratorClient(connectionInfo.getId());
        if (curatorZkClient != null && CuratorZkUtil.isConnect(curatorZkClient)) {
            informationTableCtrl.addTab(connectionInfo);
        } else {
            ZkService zkService = ZkServiceFactory.getZkService(connectionInfo.getId());
            zkService.startAndAlert(connectionInfo, progressAlertCtrl);
            zkService.stateProperty().addListener((obv, ov, nv) -> {
                if (Worker.State.SUCCEEDED.equals(nv)) {
                    informationTableCtrl.addTab(connectionInfo);
                }
            });
        }
    }
}
